package com.shanzhu.book.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;

@Configuration
public class RabbitMQConfig {

    // 预约队列
    public static final String SEAT_RESERVATION_QUEUE = "seat.reservation.queue";
    // 取消预约队列
    public static final String SEAT_CANCEL_QUEUE = "seat.cancel.queue";
    // 预约交换器
    public static final String SEAT_EXCHANGE = "seat.exchange";
    // 预约路由键
    public static final String RESERVATION_ROUTING_KEY = "seat.reservation";
    // 取消预约路由键
    public static final String CANCEL_ROUTING_KEY = "seat.cancel";

    @Bean
    public Queue reservationQueue() {
        return new Queue(SEAT_RESERVATION_QUEUE, true);
    }

    @Bean
    public Queue cancelQueue() {
        return new Queue(SEAT_CANCEL_QUEUE, true);
    }

    @Bean
    public TopicExchange seatExchange() {
        return new TopicExchange(SEAT_EXCHANGE);
    }

    @Bean
    public Binding reservationBinding() {
        return BindingBuilder.bind(reservationQueue())
                .to(seatExchange())
                .with(RESERVATION_ROUTING_KEY);
    }

    @Bean
    public Binding cancelBinding() {
        return BindingBuilder.bind(cancelQueue())
                .to(seatExchange())
                .with(CANCEL_ROUTING_KEY);
    }

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(jsonMessageConverter());
        return rabbitTemplate;
    }
}